Lesson 4 - Operators

Operators are part of expressions and are used to calculate values. The order of operators are evaluated in are specified from left to right doing brackets first. Operators will only work on certain data types and it is important to ensure that operators always work on the same data type. The code below causes an error as it is trying to add a number to a string. Because the data types differ the operator can not perform the calculation. To fix this you will have to cast the string to a integer.


# this line will cause an error
print 12 + "43"
# the following line will fix this problem by casting
print 12 + str("43")


Strings will not work with certain operators. Mainly the maths operators. This is because it makes no sense to multiply letters together (what would be the result?). Also logical operators can only be used on boolean (true and false) values.

As a programmer you must always ensure that when you are dealing with operators that all of the data types match. In order to make this easier it helps to name variables with meaningful names. Have a look at the two code examples below. Which one is easier to read? Although not necessary it will make code easier to read and maintain. It will help reduce errors with data types.


# example 1 - poor variable names
x = "Henry"
y = 34
if (y > 30):
	print "Wow, " + x + " is old! He is " + str(y)
# example 2 - good variable names
name = "Henry"
age = 34
if (age > 30):
	print "Wow, " + name + " is old! He is " + str(age)


Variable names can not start with a symbol or a number. However they can contain numbers and the _ (underscore) symbol. The code will not compile if you use an invalid variable name. Also variables must not contain spaces. If you want to use a variable name which contains multiple words then you can mix upper and lower case. The example below demonstrates this


multipleWordVariable = "hello"

Sometimes it may not be clear which operator to run first. In these cases operator precedence will take over. This specify's the order which operators are considered. For example * and / are considered before + and -. Also making a value negative is considered before anything else. Look at the operator precedence table to get a complete idea on how operators are evaluated. Also look at the code below.


print  4 + 2 * 3 # prints 10
print -4 + 3 * 2 # prints 2
print -(4 + 3 * 2) # prints -10 

Key learning points